# coding: utf-8
# @Time : 2021/7/30 9:23
# @Author : fovegage
# @Email : fovegage@gmail.com
# @File : database_migrate.py
# -*- coding: utf-8 -*-
import os
import sys
import pandas as pd
import requests
import re
import json
from urllib.parse import urlsplit, parse_qsl
from bs4 import BeautifulSoup
import json

pwd = os.path.dirname(os.path.dirname(__file__))

# 进入django设置
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.settings')
import json
import django

django.setup()

from goods.models import Product, Good

# spg修改
# update goods_product set spg_id = 10;
# t = "{\"skuId\": 10029242613825, \"\\u4ea7\\u54c1\": \"\\u8d4b\\u6d3b\\u7115\\u5f69\\u7ef4\\u4ed6\\u547d\\u7cbe\\u534e30ml\\u6db2\"}"

# print(json.loads(t))

"""
[{"value": "赋活焕彩维他命精华30ml液","productAttributeId": 19}]
[{"value": "补水","productParamId": 1}]
[{"key":"产品","value":"赋活焕彩维他命精华30ml液"}]
"""


def step1():
    for good in Good.objects.all():
        try:
            params = good.params

            value = json.loads(params)['产品']
            per = [{'key': '产品', 'value': value}]

            good.params = per
            good.save()
        except:
            continue


def step2():
    # [{"value": "赋活焕彩维他命精华30ml液","productAttributeId": 19}]
    for product in Product.objects.all():
        try:
            temp = []

            goods = product.goods.all()
            for good in goods:
                params = good.params
                for param in params:
                    temp.append(param['value'])

            # 可以有多个属性 数组
            product.attrs = [{"value": ",".join(temp), "productAttributeId": 19}]
            product.save()
        except:
            continue


def get_images(url):
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'
    }
    # url = 'https://npcitem.jd.hk/31497066274.html#crumb-wrap'
    rep = requests.get(url, headers=headers).content.decode()
    soup = BeautifulSoup(rep, 'lxml')
    imgs = ['https://img13.360buyimg.com/cms/' + x.get('data-url') for x in soup.select('#spec-list > ul > li > img')]
    # print(imgs)
    # return json.dumps(imgs)
    return imgs


import time


def step3():
    for product in Product.objects.all():
        try:
            time.sleep(0.3)
            goods = product.goods.all()
            temp = []
            print(product.id)
            for good in goods:
                url = good.data_url
                imgs = get_images(url)
                good.cover = imgs[0]
                good.save()
                temp.extend(imgs)
            temp = temp[:5] if len(temp) >= 5 else temp
            product.images = ','.join(temp)
            product.save()
        except:
            continue


def step4():
    for product in Product.objects.all():
        product.detail = product.goods.first()
        product.save()


if __name__ == '__main__':
    step2()
